# cython: language_level=3
import app.model_phl.my_tool_package as my_package
# import util_log
import datetime
import app.utils as utils
import app.utils.util_log as util_log
from app.data import RedisUtils


# from app.data import AdvanceDataTools

def get_is_rule_featues(freatures, key):
    if 'none' == freatures.get(key, 'none') or freatures.get(key, 'none') is None:
        util_log.get_logger().debug('get_is_rule_featues {} error'.format(key))
        return False
    else:
        return True


class NewCustomerRules(object):
    """
    纯新客规则
    """

    def __int__(self):
        pass

    def initial_abtest(self, free_features):
        """
        abtest分流
        :param free_features:
        :return:
        """
        redis_util = RedisUtils()
        # redis_key = f"NEW_CUSTOMER_APPLY_CNT_{utils.datetime_to_str(datetime.date.today())}"
        # redis_util.increase(redis_key, 1)
        # apply_cnt = redis_util.get(redis_key)
        # apply_cnt_value = 0 if apply_cnt is None else int(apply_cnt)
        # blind_test_split = utils.split_by_cnt(apply_cnt_value,[1, 3, 5, 7, 9])
        blind_test_split_v2 = 1
        free_features['blind_test_split_v2'] = blind_test_split_v2

        if blind_test_split_v2 == 1:
            # 盲放策略
            redis_key = f"BLIND_TEST_NEW_CUSTOMER_APPLY_CNT_{utils.datetime_to_str(datetime.date.today())}"
            redis_util.increase(redis_key, 1)
            apply_cnt = redis_util.get(redis_key)
            apply_cnt_value = 0 if apply_cnt is None else int(apply_cnt)
            blind_test_pass = utils.split_by_cnt(apply_cnt_value, [1, 3, 5, 7, 9])  # 40通过率
            free_features['blind_test_pass'] = blind_test_pass

    def rules(self, free_features):
        """
        纯新客规则
        :param free_features:
        :return:
        """
        rule_sets_result = {}
        rule_result = self.__ordinary_rule__(free_features=free_features)
        rule_sets_result.update(rule_result)
        # score_result = self.__score_rule__(free_features=free_features)
        # rule_sets_result.update(score_result)

        return rule_sets_result

    def preloan_amount(self, free_features, FraudAssessmentResults):
        """
        纯新客额度
        :param free_features:
        :param FraudAssessmentResults:
        :return:
        """
        blind_test_split_v2 = free_features.get('blind_test_split_v2', 0)
        if blind_test_split_v2 == 1:
            return self.__blindtest_amount__(free_features=free_features, FraudAssessmentResults=FraudAssessmentResults)
        else:
            return self.__preloan_amount__(free_features=free_features, FraudAssessmentResults=FraudAssessmentResults)

    def __blindtest_amount__(self, free_features, FraudAssessmentResults):
        """
        额度策略
        :param free_features:
        :param FraudAssessmentResults:
        :return:
        """
        amount = 0

        if FraudAssessmentResults == 'reject':
            return amount

        amount = 1500

        return amount

    def __preloan_amount__(self, free_features, FraudAssessmentResults):
        """
        额度策略
        :param free_features:
        :param FraudAssessmentResults:
        :return:
        """
        amount = 0

        if FraudAssessmentResults == 'reject':
            return amount

        creditScoreNewV2 = free_features.get('creditScoreNewV2', 0)

        if creditScoreNewV2 <= 571:
            amount = 2000
        elif 571 < creditScoreNewV2 <= 589:
            amount = 2500
        elif 589 < creditScoreNewV2 <= 604:
            amount = 3000
        elif 604 < creditScoreNewV2 <= 623:
            amount = 3500
        elif 623 < creditScoreNewV2 <= 999:
            amount = 4000
        return amount

    def __score_rule__(self, free_features):
        """
        信用分规则
        :param free_features:
        :return:
        """
        rule_sets_result = {}

        creditScoreNewV2 = free_features.get('creditScoreNewV2', 0)

        # 信用评分规则,针对不同的包设置不同的阈值
        if creditScoreNewV2 <= 465:
            rule_sets_result['m501'] = 1

        return rule_sets_result

    def __blind_test_rule__(self, free_features):
        """
        纯新客策略(盲放规则）
        :param free_features:
        :return:
        """
        rule_sets_result = {}
        blind_test_pass = free_features.get('blind_test_pass', 0)

        if blind_test_pass != 1:
            rule_sets_result['m777'] = 1

        if free_features.get('userMediaSource', '') == 'organic' or free_features.get('userMediaSource',
                                                                                      'None') == 'None':
            rule_sets_result['m601'] = 1

        if free_features.get('userPackageId', '') == 'micro.loan.app':
            rule_sets_result['m601'] = 1

        # if len(rule_sets_result) == 0: #上面的规则过了之后，才调用收费的陪跑规则
        #     tools = AdvanceDataTools()
        #     user_mobile = free_features.get('USER_MOBILE','')
        #     user_ocr_card_type = free_features.get('USER_OCR_CARD_TYPE','')
        #     user_ocr_card_no = free_features.get('USER_OCR_CARD_NO','')
        #     user_ocr_card_name = free_features.get('USER_OCR_CARD_NAME','')
        #     user_ocr_card_birthday = free_features.get('USER_OCR_CARD_BIRTHDAY','')

        #     id_number = user_ocr_card_no.replace('-','').upper()

        #     social_media_result = tools.social_media_detection(phone_number=user_mobile)
        #     tele_status_result = tools.tele_status_check(phone_number=user_mobile)
        #     black_list_result = tools.black_list(name=user_ocr_card_name,idType=user_ocr_card_type,idNumber=id_number,phoneNumber=user_mobile,birthday=user_ocr_card_birthday)

        #     advance_data = dict()
        #     advance_data['social'] = social_media_result
        #     advance_data['tele'] = tele_status_result
        #     advance_data['black'] = black_list_result

        #     free_features['advance_data'] = advance_data

        return rule_sets_result

    def __ordinary_rule__(self, free_features):
        """
        非白名单先拒绝
        :param free_features:
        :return:
        """
        rule_sets_result = {}
        # 准入规则

        # 准入规则
        if get_is_rule_featues(free_features, 'age') and (
                (free_features['age'] > 0 and free_features['age'] < 18) or free_features[
            'age'] > 65):
            rule_sets_result['m101'] = 1
        if get_is_rule_featues(free_features, 'on_loan_not_yet_cnt') and free_features['on_loan_not_yet_cnt'] > 0:
            rule_sets_result['m102'] = 1

        # 欺诈规则
        # if get_is_rule_featues(free_features, 'con_contact_cnt') and free_features['con_contact_cnt'] >= 10:
        #     rule_sets_result['m201'] = 1

        if get_is_rule_featues(free_features, 'biz_devRegCnt_1w') and free_features['biz_devRegCnt_1w'] >= 10:
            rule_sets_result['m202'] = 1

        if get_is_rule_featues(free_features, 'biz_devRegCnt_1d') and free_features['biz_devRegCnt_1d'] >= 10:
            rule_sets_result['m203'] = 1

        if get_is_rule_featues(free_features, 'biz_gpsRegCnt_1d') and free_features['biz_gpsRegCnt_1d'] >= 10:
            rule_sets_result['m204'] = 1

        if get_is_rule_featues(free_features, 'biz_ipRegCnt_1d') and free_features['biz_ipRegCnt_1d'] >= 10:
            rule_sets_result['m205'] = 1

        if get_is_rule_featues(free_features, 'biz_fbid_cnt') and free_features['biz_fbid_cnt'] >= 5:
            rule_sets_result['m206'] = 1

        if get_is_rule_featues(free_features, 'bankcard_associated_phone_cnt') and free_features[
            'bankcard_associated_phone_cnt'] >= 10:
            rule_sets_result['m207'] = 1

        if get_is_rule_featues(free_features, 'con_contact_fraudlevel1_cnt') and free_features[
            'con_contact_fraudlevel1_cnt'] >= 999:
            rule_sets_result['m208'] = 1

        if get_is_rule_featues(free_features, 'major_phone_majorfraud_cnt') and free_features[
            'major_phone_majorfraud_cnt'] >= 999:
            rule_sets_result['m209'] = 1

        # 3 黑名单
        if get_is_rule_featues(free_features, 'inner_black_phone') and free_features['inner_black_phone'] == 1:
            rule_sets_result['m301'] = 1

        if get_is_rule_featues(free_features, 'inner_black_idCard') and free_features['inner_black_idCard'] == 1:
            rule_sets_result['m302'] = 1

        if get_is_rule_featues(free_features, 'inner_black_macCode') and free_features['inner_black_macCode'] == 1:
            rule_sets_result['m303'] = 1

        if get_is_rule_featues(free_features, 'inner_black_gaid') and free_features['inner_black_gaid'] == 1:
            rule_sets_result['m304'] = 1

        if get_is_rule_featues(free_features, 'inner_black_ip') and free_features['inner_black_ip'] == 1:
            rule_sets_result['m305'] = 1

        if get_is_rule_featues(free_features, 'inner_black_gps') and free_features['inner_black_gps'] == 1:
            rule_sets_result['m306'] = 1

        if get_is_rule_featues(free_features, 'overdue_sms_cnt') and free_features['overdue_sms_cnt'] == 90:
            rule_sets_result['m307'] = 1

        if get_is_rule_featues(free_features, 'is_gongzhai_overdue_orders') and free_features[
            'is_gongzhai_overdue_order'] == 1:
            rule_sets_result['m308'] = 1

        if get_is_rule_featues(free_features, 'outer_black_blurry_namebirthday') and free_features[
            'outer_black_blurry_namebirthday'] == 1:
            rule_sets_result['m309'] = 1

        if get_is_rule_featues(free_features, 'outer_black_blurry_idcard') and free_features[
            'outer_black_blurry_idcard'] == 1:
            rule_sets_result['m310'] = 1

        # 其他策略集
        if get_is_rule_featues(free_features, 'biz_black_GidDevice') and free_features[
            'biz_black_GidDevice'] != None and free_features['biz_black_GidDevice'] > 0:
            rule_sets_result['m401'] = 1

        if get_is_rule_featues(free_features, 'LAST_refuse001') and free_features['LAST_refuse001'] >= 31:
            rule_sets_result['m402'] = 1

        if get_is_rule_featues(free_features, 'app_riskLoanAppCnt') and free_features['app_riskLoanAppCnt'] > 0:
            rule_sets_result['m403'] = 1

        if get_is_rule_featues(free_features, 'app_loan_maxDays') and free_features['app_loan_maxDays'] >= 999:
            rule_sets_result['m404'] = 1

        if get_is_rule_featues(free_features, 'biz_max_expire_day_all_real_idcard_history') and free_features[
            'biz_max_expire_day_all_real_idcard_history'] > 2:
            rule_sets_result['m405'] = 1

        if get_is_rule_featues(free_features, 'biz_max_expire_day_all_phone_history') and free_features[
            'biz_max_expire_day_all_phone_history'] > 2:
            rule_sets_result['m406'] = 1

        if get_is_rule_featues(free_features, 'app_loan_medianDays') and free_features['app_loan_medianDays'] >= 999:
            rule_sets_result['m407'] = 1

        if get_is_rule_featues(free_features, 'biz_devLoanCnt') and free_features['biz_devLoanCnt'] == 1:
            rule_sets_result['m408'] = 1

        if get_is_rule_featues(free_features, 'biz_maxDpd') and free_features['biz_maxDpd'] > 2:
            rule_sets_result['m409'] = 1

        if get_is_rule_featues(free_features, 'biz_curDefault') and free_features['biz_curDefault'] > 0:
            rule_sets_result['m410'] = 1

        if get_is_rule_featues(free_features, 'biz_lastOrderDpd') and free_features['biz_lastOrderDpd'] > 2:
            rule_sets_result['m411'] = 1

        if get_is_rule_featues(free_features, 'app_inst_d3_cnt') and free_features['app_inst_d3_cnt'] >= 31:
            rule_sets_result['m412'] = 1

        if get_is_rule_featues(free_features, 'whitelist_first_time_diff_days') and free_features[
            'whitelist_first_time_diff_days'] >= 31:
            rule_sets_result['m413'] = 1

        if get_is_rule_featues(free_features, 'max_overdue_days') and free_features[
            'max_overdue_days'] > 2:
            rule_sets_result['m413'] = 1

        if get_is_rule_featues(free_features, 'biz_max_expire_day_all_phone_cur') and free_features[
            'biz_max_expire_day_all_phone_cur'] > 0:
            rule_sets_result['m420'] = 1

        if get_is_rule_featues(free_features, 'biz_max_expire_day_all_real_idcard_cur') and free_features[
            'biz_max_expire_day_all_real_idcard_cur'] > 0:
            rule_sets_result['m421'] = 1



        # 对于非白名单先拒绝
        if get_is_rule_featues(free_features, 'in_white_list') and free_features['in_white_list'] == 0:
            rule_sets_result['m601'] = 1

        return rule_sets_result
